#include "ui/HistoryWidget.h"
#include "database/DatabaseManager.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QJsonArray>
#include <QJsonObject>

HistoryWidget::HistoryWidget(QWidget *parent) : QWidget(parent)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    
    m_table = new QTableWidget;
    m_table->setColumnCount(5);
    m_table->setHorizontalHeaderLabels({"版本ID", "时间", "项目", "状态", "操作"});
    layout->addWidget(m_table);
    
    refresh();
}

void HistoryWidget::refresh()
{
    m_table->setRowCount(0);
    
    QJsonArray history = DatabaseManager::instance().getObfuscationHistory(50);
    for (const QJsonValue &value : history) {
        QJsonObject record = value.toObject();
        int row = m_table->rowCount();
        m_table->insertRow(row);
        
        m_table->setItem(row, 0, new QTableWidgetItem(record["version_id"].toString()));
        m_table->setItem(row, 1, new QTableWidgetItem(record["timestamp"].toString()));
        m_table->setItem(row, 2, new QTableWidgetItem(record["project_path"].toString()));
        m_table->setItem(row, 3, new QTableWidgetItem(record["status"].toString()));
        
        QPushButton *rollbackBtn = new QPushButton("回滚");
        QString versionId = record["version_id"].toString();
        connect(rollbackBtn, &QPushButton::clicked, [this, versionId]() {
            emit rollbackRequested(versionId);
        });
        m_table->setCellWidget(row, 4, rollbackBtn);
    }
}